<?php

namespace App\Http\Controllers\Backend;

use App\Models\Admin;
use App\Models\Article;
use App\Models\ArticleAddon;
use App\Models\SiteConfig;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

class SettingController extends BaseController
{
    // 话题
    public function initialize()
    {
        parent::initialize();

        $this->model = 'SiteInfo';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作

    // 配置
    public function setting()
    {
        $list = Config::get('site');

        return $this->success($list);
    }


    // 获取配置
    public function config()
    {
        $model = new SiteConfig();
        $list  = $model->isCache(true)->getConfig();

        return $this->success($list);
    }

    // 保存配置
    public function save()
    {
        // 参数
        $data = $this->data;
        $data = $this->filterNull($data);
        $this->throwIf(empty($data), "请传递需要修改的数据！");

        // 获取配置
        $model = new SiteConfig();
        $list  = $model->isCache(true)->get()->toArray();
        $list  = array_column($list, null, 'field');
        $table = 'site_config';


        // 保存数据
        DB::beginTransaction();
        try{
            foreach($data as $field => $val){
                $info = $list[$field] ?? [];

                // 添加
                if(empty($info)){
                    // 更新新数据
                    $setArr = ["field" => $field, "cn_value" => $val];
                    $result = DB::table($table)->insert($setArr);
                    if($result === false){
                        throw  new \Exception('保存配置信息失败！！');
                    }
                } else{
                    // 修改
                    $result = DB::table($table)->where(['id' => $info['id']])->update(["cn_value" => $val]);
                    if($result === false){
                        throw  new \Exception('修改原来的配置信息失败！！');
                    }
                }
            }

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();
            $this->throwIf(true, $e->getMessage());
        }

        // 删除缓存
        $model->deleteCacheList($list);

        return $this->success();
    }

    // 统计
    public function census()
    {
        $where   = [["role", "like", '%"article"%'], ["status", '=', "1"]];
        $where   = [["status", '=', "1"]];
        $adminDb = new Admin();
        $field   = ["id", "username", "nickname"];
        $list    = $adminDb->where($where)->select($field)->orderBy("ctime", 'desc')->get()->toArray();

        // 查询数据
        $map1    = ["status" => 1, "is_original" => 1,];
        $map2    = ["status" => 1, "is_original" => 1, "month" => date('Ym')];
        $map3    = ["status" => 1, "is_original" => 1, "week" => date('YW')];
        $map4    = ["status" => 1, "is_original" => 1, "day" => date('Ymd')];
        $addonDb = new ArticleAddon();
        $totals  = $addonDb->where($map1)->groupBy('uid')->selectRaw("uid,count(id) number")->get()->toArray();
        $months  = $addonDb->where($map2)->groupBy('uid')->selectRaw("uid,count(id) number")->get()->toArray();
        $weeks   = $addonDb->where($map3)->groupBy('uid')->selectRaw("uid,count(id) number")->get()->toArray();
        $days    = $addonDb->where($map4)->groupBy('uid')->selectRaw("uid,count(id) number")->get()->toArray();
        $totals  = array_column($totals, 'number', 'uid');
        $months  = array_column($months, 'number', 'uid');
        $weeks   = array_column($weeks, 'number', 'uid');
        $days    = array_column($days, 'number', 'uid');

        // 整理
        $result = [];
        foreach($list as $k => $v){
            $uid = $v["id"];
            // 数据
            $v["total_nums"] = $totals[$uid] ?? 0;
            $v["month_nums"] = $months[$uid] ?? 0;
            $v["week_nums"]  = $weeks[$uid] ?? 0;
            $v["day_nums"]   = $days[$uid] ?? 0;

            // 组合
            $result[] = $v;
        }


        return $this->success($result);
    }

    // 个人统计（按天，按月）
    public function getCensus()
    {
        $uid   = $this->getData('uid',0,'intval');
        $dType = $this->getData('channel', 'date','trim');
        $page  = $this->page;
        $rows  = $this->rows;
        $this->throwIf(!in_array($dType, ['day', 'date', 'month', 'week']), '请指定正确按天按月统计方法！');
        $this->throwIf(empty($uid), '请指定统计的用户ID！');

        // 先查询展示的日期（用于翻页）
        // 如果直接查询的话，按channel分组，就会有同一天的数据展示下一页
        $addonDb = new ArticleAddon();
        $where   = [['uid', '=', $uid], ['status', '=', 1], ['is_original', '=', 1]];
        $dates   = $addonDb->where($where)->distinct()->forPage($page, $rows)->pluck($dType)->toArray();

        // 在查询列表展示（每个栏目都要有数据）
        $field = "uid, $dType, channel, count(id) number, sum(read_no) read_num, sum(read_pc) pc_number, sum(read_ios) ios_number, sum(read_android) android_number, sum(read_h5) h5_number";
        $list  = $addonDb->where($where)->whereIn($dType, $dates)->groupBy('uid', 'channel', $dType)->forPage($page, $rows)
                         ->selectRaw($field)->get()->toArray();

        // 整理数据
        $result = [];
        $row    = [
            'uid'              => $uid,
            //'date'             => '2022-12-26',
            // 总数
            'number'           => 0,
            'read_num'         => 0,
            // 频道1
            'read_num_1'       => 0,
            'pc_number_1'      => 0,
            'ios_number_1'     => 0,
            'android_number_1' => 0,
            'h5_number_1'      => 0,
            // 频道2
            'read_num_2'       => 0,
            'pc_number_2'      => 0,
            'ios_number_2'     => 0,
            'android_number_2' => 0,
            'h5_number_2'      => 0,
            // 频道3
            'read_num_3'       => 0,
            'pc_number_3'      => 0,
            'ios_number_3'     => 0,
            'android_number_3' => 0,
            'h5_number_3'      => 0,
            // 频道4
            'read_num_4'       => 0,
            'pc_number_4'      => 0,
            'ios_number_4'     => 0,
            'android_number_4' => 0,
            'h5_number_4'      => 0,
        ];
        foreach($list as $item){
            // 获取基本数据
            $channel     = $item['channel'];
            $dateField   = $item[$dType];
            $row[$dType] = $dateField; // 构建每一行的日期
            // 构建返回数据
            $result[$dateField] = $result[$dateField] ?? $row;
            // 整理数据：总数
            $result[$dateField]['number']   += $item['number'];
            $result[$dateField]['read_num'] += $item['read_num'];
            // 频道数据
            $result[$dateField]['read_num_'.$channel]       += $item['read_num'];
            $result[$dateField]['pc_number_'.$channel]      += $item['pc_number'];
            $result[$dateField]['ios_number_'.$channel]     += $item['ios_number'];
            $result[$dateField]['android_number_'.$channel] += $item['android_number'];
            $result[$dateField]['h5_number_'.$channel]      += $item['h5_number'];
        }

        return $this->success(array_values($result));
    }

}


